package cContext

import (
	"context"

	"gitee.com/csingo/cHelper"

	"github.com/gin-gonic/gin"
	"google.golang.org/grpc/metadata"

	"gitee.com/csingo/cCommon"
)

func GinToGrpc(ctx *gin.Context) (c context.Context) {
	var md metadata.MD
	data, ok := ctx.Get(cCommon.GRPC_Metadata)
	if ok {
		md = data.(metadata.MD)
	} else {
		md = make(metadata.MD)
	}

	for k, v := range ctx.Keys {
		switch k.(type) {
		case string:
			kitem := k.(string)
			if cHelper.InArray(grpc_ignore_metadata_keys, kitem) {
				continue
			}
			md.Set(kitem, cHelper.ToString(v))
		}
	}

	c = metadata.NewOutgoingContext(ctx, md)

	return
}

func GrpcToGin(ctx context.Context) (c *gin.Context) {
	c = New()
	md, ok := metadata.FromIncomingContext(ctx)
	if ok {
		for k, v := range md {
			if len(v) > 0 {
				c.Set(k, v[0])
			} else {
				c.Set(k, "")
			}
		}
		c.Set(cCommon.GRPC_Metadata, md)
		c.Set(cCommon.GRPC_Context, ctx)
	}

	return
}

func AppendGrpcIgnoreMetadataKeys(keys ...string) {
	grpc_ignore_metadata_keys = append(grpc_ignore_metadata_keys, keys...)
}
